package com.bitcat.firstapp.demo.permissiondemo

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityPermissionDemoBinding
import com.permissionx.guolindev.PermissionX
import es.dmoral.toasty.Toasty
import java.io.File

//权限案例
class PermissionDemoActivity : AppCompatActivity() {

    private val binding: ActivityPermissionDemoBinding by lazy {
        ActivityPermissionDemoBinding.inflate(layoutInflater)
    }

    //拍照
    private val cameraPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
        if (it){
            takePhoto()
        }else{
           handlePermissionDenied(android.Manifest.permission.CAMERA)
        }
    }

    //拍照
    private val takePhotoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
        if (it.resultCode == RESULT_OK){
            binding.ivPreview.setImageURI(photoUri)
        }
    }

    var photoUri:Uri? = null

    //拍照
    private fun takePhoto() {
        //1. 创建一个空的图片文件
        val photoFile = createImageFile()

        //2. 打开相机
        photoUri = FileProvider.getUriForFile(this,"${packageName}.fileprovider",photoFile)


        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        intent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri)
        takePhotoLauncher.launch(intent)
    }


    private val pickImageLauncher = registerForActivityResult(ActivityResultContracts.PickVisualMedia()){
        it?.let { binding.ivPreview.setImageURI(it) }
    }

    //存储权限申请
    private val storagePermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
        isGranted ->
        if (isGranted){
            //打开相册
            openGalleryLegacy()
        }else{
            handlePermissionDenied(android.Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }



    private fun createImageFile(): File {
        val timeStamp = System.currentTimeMillis()
        val imageFileName = "JPEG_${timeStamp}"
        val storageDir = getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES)
        return File.createTempFile(imageFileName,".jpg",storageDir)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(20, systemBars.top, 20, systemBars.bottom)
            insets
        }

        setupClickListeners()
    }

    //点击事件
    private fun setupClickListeners() {

        //打开相机
        binding.btnTakePhoto.setOnClickListener {
            checkAndRequestCameraPermission()
        }

        //打开相册
        binding.btnOpenGallery.setOnClickListener {
            openGallery()
        }

        //Permissonx打开相机
        binding.btnTakePhotoX.setOnClickListener {
            checkAndRequestCameraPermissionX()
        }

        binding.btnOpenGalleryX.setOnClickListener {
            openGalleryX()
        }
    }

    private fun openGalleryX() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
            //Android13 photo picker
            pickImageLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }else{
            //Android13以下
            PermissionX.init(this)
                .permissions(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                .explainReasonBeforeRequest()
                .onExplainRequestReason{scope,deniedlist->  //拒绝后，弹窗向用户说明，为什么需要这个权限，再次点击
                    scope.showRequestReasonDialog(
                        deniedlist,
                        "需要存储权限来打开相册",
                        "确定",
                        "取消"
                    )
                }
                .onForwardToSettings{       //被永久拒绝，只能提示用户自己去设置中手动开启
                        scope,deniedList->
                    scope.showForwardToSettingsDialog(
                        deniedList,
                        "您需要去设置中手动开启存储权限",
                        "确定",
                        "取消"
                    )
                }
                .request{
                        allGranted,grantedList, deniedList ->
                    if (allGranted){
                        openGalleryLegacy()
                    }else{
                        Toasty.info(this,"您拒绝了存储权限申请").show()
                    }
                }
        }
    }

    private fun checkAndRequestCameraPermissionX() {
        PermissionX.init(this)
            .permissions(android.Manifest.permission.CAMERA)
            .explainReasonBeforeRequest()
            .onExplainRequestReason{scope,deniedlist->  //拒绝后，弹窗向用户说明，为什么需要这个权限，再次点击
                scope.showRequestReasonDialog(
                    deniedlist,
                    "需要相机权限来拍照",
                    "确定",
                    "取消"
                )
            }
            .onForwardToSettings{       //被永久拒绝，只能提示用户自己去设置中手动开启
                scope,deniedList->
                scope.showForwardToSettingsDialog(
                    deniedList,
                    "您需要去设置中手动开启相机权限",
                    "确定",
                    "取消"
                )
            }
            .request{
                allGranted,grantedList, deniedList ->
                if (allGranted){
                    takePhoto()
                }else{
                    Toasty.info(this,"您拒绝了相机权限申请").show()
                }
            }
    }

    private fun openGallery() {
        openGalleryLegacy()

//        //1.判断用户的手机系统版本  13以下还是13以上
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU){
//            //Android13  photo picker
//            val request = PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)
//            pickImageLauncher.launch(request)
//        }else{
//            //Android13以下
//            if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
//                //有权限,打开相册
//                openGalleryLegacy()
//            }else{
//                //没权限，申请权限
//                storagePermissionLauncher.launch(android.Manifest.permission.READ_EXTERNAL_STORAGE)
//            }
//        }
    }

    private fun openGalleryLegacy() {
        val intent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(intent,100)
    }

    //判断是否有拍照权限
    private fun checkAndRequestCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
            takePhoto()
        }else{
            cameraPermissionLauncher.launch(android.Manifest.permission.CAMERA)
        }
    }

    private fun handlePermissionDenied(permission:String){
        //单次拒绝 还是 永久拒绝
        // 单次拒绝，可以自己弹一个窗，告知用户，为什么App需要这个权限
        //永久拒绝 引导用户去设置页面打开权限
        val permissionType = when(permission){
            android.Manifest.permission.CAMERA -> "相机"
            else -> "相册"
        }

        if (shouldShowRequestPermissionRationale(permission)){
            //单次拒绝
            showPermissionDeniedMessage(permissionType)
        }else{
            //永久拒绝
            showSettingsDialog(permissionType)
        }
    }

    // 权限被拒绝时的提示
    private fun showPermissionDeniedMessage(permissionType: String) {
        AlertDialog.Builder(this)
            .setTitle("权限被拒绝")
            .setMessage("需要${permissionType}权限才能使用此功能。")
            .setPositiveButton("确定", null)
            .show()
    }

    // 跳转到应用设置页
    private fun showSettingsDialog(permissionType: String) {
        AlertDialog.Builder(this)
            .setTitle("需要权限")
            .setMessage("应用需要${permissionType}权限才能正常工作。请在设置中手动开启权限。")
            .setPositiveButton("去设置") { _, _ ->
                openAppSettings()
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun openAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
        intent.data = Uri.fromParts("package", packageName, null)
        startActivity(intent)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == RESULT_OK){
            data?.data?.let {
                binding.ivPreview.setImageURI(it)
            }
        }
    }
}